<template>
  <div>
    <!-- 面包屑头部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert title="只允许设置第三级相关参数" type="warning" closable show-icon></el-alert>

      <!-- 级联选择 -->
      <div style="margin-top:20px;">
        请选择商品分类:
        <el-cascader
          v-model="selectOptionArr"
          :options="cascaderList"
          :props="cascaderProps"
          @change="cascaderChange"
          clearable
        ></el-cascader>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="showAddParamsDialog"
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
          >添加参数</el-button>
          <!-- 动态参数列表 -->
          <el-table :data="manyTabList" border stripe>
            <!-- expand展开列 index索引列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="removeAttr(i,scope.row)"
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                >{{item}}</el-tag>
                <el-input
                  style="width:120px;"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作" width="180">
              <template slot-scope="item">
                <!-- 编辑按钮 -->
                <el-button
                  @click="showEditParamsDialog(item.row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  @click="delParams(item.row)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="showAddParamsDialog"
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
          >添加属性</el-button>
          <!-- 静态属性列表 -->
          <el-table :data="onlyTabList" border stripe>
            <!-- expand展开列 index索引列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                <el-input
                  style="width:120px;"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" width="180">
              <template slot-scope="item">
                <!-- 编辑按钮 -->
                <el-button
                  @click="showEditParamsDialog(item.row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  @click="delParams(item.row)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="activeName=='many'?'添加动态参数':'添加静态属性'"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="resetAddParamsForm"
    >
      <!-- 内容主体部分  model当前表单数据 rules校验规则 ref拿到元素 prop-->
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsForm"
        label-width="120px"
      >
        <el-form-item :label="activeName=='many'?'添加动态参数':'添加静态属性'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button @click="addParamsSub" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态参数/静态属性对话框 -->
    <el-dialog
      :title="activeName=='many'?'添加动态参数':'添加静态属性'"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="resetEditParamsForm"
    >
      <!-- 内容主体部分  model当前表单数据 rules校验规则 ref拿到元素 prop-->
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsForm"
        label-width="120px"
      >
        <el-form-item :label="activeName=='many'?'添加动态参数':'添加静态属性'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button @click="editParamsSub" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cascaderList: [],
      selectOptionArr: [],
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
        // checkStrictly: true
      },
      activeName: "many",
      onlyTabList: [],
      manyTabList: [],
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: "",
        attr_sel: ""
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_name: "",
        attr_sel: ""
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      inputVisible: false,
      inputValue: ""
    };
  },

  methods: {
    //   获取数据
    async getCascaderList() {
      var res = await this.axios.get("/categories");
      console.log(res);
      if (res.meta.status == 200) {
        this.cascaderList = res.data;
      }
      console.log(this.cascaderList);
    },

    // 选择cascader之后会触发 获取分类数据
    cascaderChange() {
      this.getParams();
    },

    // 封装函数 获取参数数据
    async getParams() {
      // 当点击非三级数据时 清空数据
      if (this.selectOptionArr.length != 3) {
        this.selectOptionArr = [];
        this.manyTabList=[];
        this.onlyTabList=[];
        return;
      }
      console.log("选择了三级分类");
      //   console.log(this.cateId);
      var res = await this.axios.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      });
      if (res.meta.status == 200) {
        console.log(res.data);
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.inputVisible = false;
          item.inputValue = "";
        });
        if (this.activeName == "many") {
          this.manyTabList = res.data;
        } else {
          this.onlyTabList = res.data;
        }
      }
    },
    // 清空表单
    resetAddParamsForm() {
      this.$refs.addParamsForm.resetFields();
    },

    tabHandleClick() {
      this.getParams();
    },

    // 展示添加动态参数/静态属性对话框
    showAddParamsDialog() {
      this.addParamsDialogVisible = true;
    },
    // 提交添加动态参数/静态属性
    addParamsSub() {
      this.$refs.addParamsForm.validate(async flag => {
        if (!flag) return;
        var res = await this.axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        console.log(res);
        if (res.meta.status == 201) {
          this.$mg.success("添加成功");
          this.addParamsDialogVisible = false;
          this.getParams();
        } else {
          this.$mg.error(res.meta.msg);
        }
      });
    },

    // 展示编辑按钮对话框
    async showEditParamsDialog(row) {
      this.editParamsDialogVisible = true;
      var res = await this.axios.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      if (res.meta.status == 200) {
        this.editParamsForm = res.data;
      }
    },
    //    提交
    editParamsSub() {
      this.$refs.editParamsForm.validate(async flag => {
        if (!flag) return;
        var res = await this.axios.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        console.log(res);
        if (res.meta.status == 200) {
          this.$mg.success("添加成功");
          this.editParamsDialogVisible = false;
          this.getParams();
        } else {
          this.$mg.error("添加失败");
        }
      });
    },
    // 清空
    resetEditParamsForm() {
      this.$refs.editParamsForm.resetFields();
    },

    // 删除按钮
    delParams(row) {
      this.$cfm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await this.axios.delete(
            `categories/${this.cateId}/attributes/${row.attr_id}`
          );
          //   console.log(res);
          if (res.meta.status == 200) {
            this.$mg.success("删除成功");
            this.getParams();
          } else {
            this.$mg.error(res.meta.msg);
          }
        })
        .catch(() => {
          this.$mg.info("已取消删除");
        });
    },

    // 输入框失去焦点或按下enter键
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputVisible = false;
        row.inputValue = "";
        console.log("输入框不合法");
        return;
      }
      console.log("合法");
      row.attr_vals.push(row.inputValue)
      this.editParamsAttr(row) 
    },

    // 点击按钮,展示文本输入框
    showInput(row) {
      row.inputVisible = true;
      // $nextTick当页面dom被重新渲染后才会调用回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 封装函数 更新参数属性
    async editParamsAttr(row){
      var res=await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:this.activeName,
        attr_vals:row.attr_vals.join(',')
      })
      if(res.meta.status==200){
        this.$mg.success('更新成功')
        row.inputVisible = false;
        row.inputValue = "";
      }else{
        this.$mg.error('更新失败')
      }
    },

    // 输出参数下的属性
    removeAttr(i,row){
      row.attr_vals.splice(i,1);
      this.editParamsAttr(row)
    }
  },

  created() {
    this.getCascaderList();
  },

  computed: {
    //   按钮禁用
    isBtnDisabled() {
      if (this.selectOptionArr.length == 3) {
        return false;
      }
      return true;
    },

    // 拿到三级分类id 以方法定义 属性使用
    cateId() {
      if (this.selectOptionArr.length == 3) {
        return this.selectOptionArr[2];
      }
      return null;
    }
  }
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
</style>
